using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Autofac;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Sqlite;
using Volo.Abp.Modularity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
using Matrix.Configuration;

namespace Matrix.Configuration
{
    /// <summary>
    /// Matrix Configuration集成测试模块
    /// </summary>
    [DependsOn(
        typeof(AbpAutofacModule),
        typeof(AbpEntityFrameworkCoreModule),
        typeof(AbpEntityFrameworkCoreSqliteModule),
        typeof(MatrixConfigurationEntityFrameworkCoreModule),
        typeof(MatrixConfigurationApplicationModule),
        typeof(MatrixConfigurationDomainModule)
    )]
    public class MatrixConfigurationIntegrationTestModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            // 配置SQLite内存数据库
            Configure<AbpDbContextOptions>(options =>
            {
                options.Configure(abpDbContextConfigurationContext =>
                {
                    abpDbContextConfigurationContext.DbContextOptions.UseSqlite(
                        CreateInMemoryDatabase(),
                        sqliteOptions =>
                        {
                            sqliteOptions.CommandTimeout(30);
                        });
                });
            });

            // 配置工作单元
            Configure<AbpUnitOfWorkDefaultOptions>(options =>
            {
                options.TransactionBehavior = UnitOfWorkTransactionBehavior.Enabled;
            });

            // 配置多租户
            Configure<AbpMultiTenancyOptions>(options =>
            {
                options.IsEnabled = true;
            });
        }

        private static string CreateInMemoryDatabase()
        {
            // 使用真正内存数据库，每个测试都有独立的数据库实例
            var connectionString = "Data Source=:memory:";
            return connectionString;
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            // 初始化测试数据库
            using var scope = context.ServiceProvider.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<MatrixConfigurationDbContext>();

            // 确保数据库被创建并应用迁移
            dbContext.Database.EnsureCreated();

            // 验证表是否创建成功
            var canConnect = dbContext.Database.CanConnect();
            if (!canConnect)
            {
                throw new InvalidOperationException("无法连接到测试数据库");
            }

            // 检查ConfigurationItems表是否存在
            var tableName = dbContext.Model.FindEntityType(typeof(ConfigurationItem))?.GetTableName();
            if (string.IsNullOrEmpty(tableName))
            {
                throw new InvalidOperationException("ConfigurationItem实体未正确配置");
            }
        }
    }
}